import traceback
import requests

from flask import Flask, render_template, request, g
import pymysql
import json
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    # with open('cangping.txt', 'r') as f:
    #     lines = f.readlines()
    #     date = []
    #     data1 = []
    #     data2 = []
    #     data3 = []
    #     for line in lines:
    #         if len(line) > 0:
    #             date.append(str(line[0:13]))
    #             d2 = line[20:].split(',')
    #             data1.append(int(d2[0]))
    #             data2.append(int(d2[1]))
    #             data3.append(int(d2[2].replace('\n', '')))
    # return render_template('cangping.html', date=date, data1=data1, data2=data2, data3=data3)
    return "Hello World !"


@app.route('/abc')
def abc():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='app')
    try:
        ua = request.headers.get("User-Agent")
        type = request.headers.get("PTYPE")
        info = {"logo": f"logo_{type}.png", "title": "步步ABC"}
        if type == "raz":
            info["title"] = "RAZ分级阅读"
        print(f"header type:{type}")
        type = "abc" if type is None else type
        if 'iPhone' in ua or 'iPad' in ua or 'Macintosh' in ua:
            type = f"{type}_i"
        else:
            type = f"{type}_a"
        print(f"final type:{type}")
        cursor = conn.cursor()
        try:
            # 查询最近的五条记录
            # id type(abc_i,abc_a) url time version size
            cursor.execute(f"select * from main_table where type='{type}' order by time desc limit 5")
            data = cursor.fetchall()
            datas = []
            for d in data:
                datas.append(
                    {"id": d[0], "type": d[1], "url": d[2], "version": d[3], "size": d[4], "time": d[5].timestamp()})
            dataJson = json.dumps(datas, ensure_ascii=False)

            return render_template('app_download.html', data=dataJson, info=json.dumps(info, ensure_ascii=False))
        except Exception as e:
            print(traceback.format_exc())
            return "error"
        finally:
            cursor.close()
    except Exception as e:

        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route('/insert', methods=['POST'])
def insert():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='app')
    try:
        type = request.json.get('type')
        url = request.json.get('url')
        version = request.json.get('version')
        size = request.json.get('size')
        with conn.cursor() as c:
            c.execute(f"insert main_table(type,url,version,size) values('{type}','{url}','{version}',{size})")
            conn.commit()
            c.close()
    except:
        print(traceback.format_exc())
    finally:
        conn.close()

    print(request.json)
    return {"code": 200}


@app.route("/push/demo")
def pushDemo():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        with conn.cursor() as c:
            c.execute(f"select * from history order by created desc limit 5")
            datas = c.fetchall()
            history = []
            for da in datas:
                history.append(da[1].strftime("%Y-%m-%d %H:%M:%S"))
            c.execute(f"select battery,time from battery where userid=90")
            b_data = c.fetchone()
            battery = b_data[0]
            time = b_data[1]
            c.close()
            return render_template("push_demo.html", data=history, bTime=time.strftime("%Y-%m-%d %H:%M:%S"),
                                   battery=battery)
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route("/push/action")
def pushAction():
    try:
        pushHeaders = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic MmFkYTFlZWQ1NjQyMTcxOTkyMTUwYjkyOmNmYTc1MTE3Y2UwYjYxMmRiMGE5ZDhiOA=='
        }

        result = requests.get('https://api.jpush.cn/v3/push/cid', headers=pushHeaders).json()
        cid = result['cidlist'][0]
        actionType = request.args.get("type")
        jsonData = {"cid": cid, "platform": "all", "audience": {"alias": ["666"]},
                    "message": {"msg_content": actionType, "content_type": actionType},
                    "options": {"time_to_live": 60, "apns_production": True}}

        result = requests.post('https://api.jpush.cn/v3/push', headers=pushHeaders, json=jsonData).json()
        return f"push action success ：{result}"

    except:
        print(traceback.format_exc())
        return f"push action error {traceback.format_exc()}"


@app.route('/push/success')
def pushSuccess():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        userid = request.args.get("userid")
        with conn.cursor() as c:
            c.execute(f"insert into history(userid) values({userid})")
            conn.commit()
            c.close()
        return "success"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route("/push/latest")
def pushLatest():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        with conn.cursor() as c:
            c.execute(f"select created from history order by created")
            last = c.fetchone()
            c.close()
            nowHour = datetime.now().hour
            am = [8, 9, 10, 11, 12]
            fm = [18, 19, 20, 21]
            if nowHour in am:
                if last[0].hour in fm:
                    requests.get(
                        "https://sctapi.ftqq.com/SCT217072TdGJyyWlRZQwsFiiYaK4lJ7ru.send?title=You forgot push AM "
                        "message.")
                else:
                    print('has ding')
            else:
                if last[0].hour in am:
                    requests.get(
                        "https://sctapi.ftqq.com/SCT217072TdGJyyWlRZQwsFiiYaK4lJ7ru.send?title=You forgot push PM "
                        "message.")
                else:
                    print('has ding')

        return f"success {last}"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route('/push/battery')
def pushBattery():
    conn = pymysql.connect(host='10.10.34.29', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        battery = request.args.get("battery")
        userid = request.args.get("userid")
        with conn.cursor() as c:
            c.execute(
                f"insert into battery(userid, battery) values ({userid}, {battery}) on duplicate key update battery=values(battery)")
            conn.commit()
            c.close()
        return "success"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


# @app.route('/day')
# def cangping_day():
#     with open('cangping.txt', 'r') as f:
#         lines = f.readlines()
#         date = []
#         data1 = []
#         data2 = []
#         data3 = []
#         last_day = ''
#         for line in lines:
#             if len(line) > 0:
#                 day = str(line[0:10])
#                 print(day,last_day)
#                 if day == last_day:
#                     continue
#                 last_day = day
#                 date.append(day)
#                 d2 = line[20:].split(',')
#                 data1.append(int(d2[0]))
#                 data2.append(int(d2[1]))
#                 data3.append(int(d2[2].replace('\n', '')))
#         print(f'{date}')
#     return render_template('cangping.html', date=date, data1=data1, data2=data2, data3=data3)

if __name__ == '__main__':
    app.run(host='0.0.0.0')
